﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.Web.Script.Serialization;

namespace placinfo
{
    // Start the service and browse to http://<machine_name>:<port>/Service1/help to view the service's generated help page
    // NOTE: By default, a new instance of the service is created for each call; change the InstanceContextMode to Single if you want
    // a single instance of the service to process all calls.	
    //[ServiceContract]
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]

    // NOTE: If the service is renamed, remember to update the global.asax.cs file
    public class Service1 : IService1
    {
        private readonly EventsDB _db = new EventsDB();

        // TODO: Implement the collection resource that will contain the SampleItem instances

        //[WebGet(UriTemplate = "/GetEvents", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
        public string GetCollection()
        {
            relatedEvents(new GeoLocation(45.813486, -78.330116));
            return getEventsFromDB(_db);
        }

        private string getEventsFromDB(EventsDB db)
        {
            var e = _db.Events.ToList();

            var js = new JavaScriptSerializer();

            return js.Serialize(e);
        }

        #region Public Methods

        public List<Event> relatedEvents(GeoLocation location)
        {
            List<Event> relatedEvents = new List<Event>();
            foreach (Event e in _db.Events)
            {
                double distanceInKm = e.DistanceBetweenPlaces(location);
                if (e.isRelevantTimeEvent()) // time of Event is relevant
                {
                    if (distanceInKm <= e.LocationRadius)
                    {
                        relatedEvents.Add(e);
                    }
                }

            }
            return relatedEvents;
        }

        //range in hours
        public List<Event> getEventsByTime(DateTime startTime, int range)
        {
            List<Event> relatedEvents = new List<Event>();
            foreach (Event e in _db.Events)
            {
                if (e.StartTime >= startTime)
                {
                    TimeSpan tsDiff = e.StartTime.Subtract(startTime);
                    if (tsDiff.Hours <= range)
                    {
                        relatedEvents.Add(e);
                    }
                }
            }
            return relatedEvents;
        }


        #endregion

    }
}
